import { defineStore } from 'pinia';
import { ref } from 'vue';
import Storage from '../utils/storage';

const STORAGE_KEY_THEME = 'app_theme';
const STORAGE_KEY_LANG = 'app_lang';

export type Theme = 'light' | 'dark';
export type Language = 'zh-CN' | 'en-US';

interface AppConfig {
  theme: Theme;
  lang: Language;
}

const defaultConfig: AppConfig = {
  theme: 'light',
  lang: 'zh-CN',
};

export const useAppStore = defineStore('app', () => {
  // 状态
  const theme = ref<Theme>(Storage.get(STORAGE_KEY_THEME) || defaultConfig.theme);
  const lang = ref<Language>(Storage.get(STORAGE_KEY_LANG) || defaultConfig.lang);
  const loading = ref(false);

  // 设置主题
  const setTheme = (newTheme: Theme) => {
    theme.value = newTheme;
    Storage.set(STORAGE_KEY_THEME, newTheme);
    // 在body上添加主题class
    document.body.className = \`theme-\${newTheme}\`;
  };

  // 设置语言
  const setLang = (newLang: Language) => {
    lang.value = newLang;
    Storage.set(STORAGE_KEY_LANG, newLang);
  };

  // 设置全局加载状态
  const setLoading = (status: boolean) => {
    loading.value = status;
  };

  // 初始化应用配置
  const initApp = () => {
    // 设置主题
    setTheme(theme.value);
    // 设置语言
    setLang(lang.value);
  };

  // 重置应用配置
  const resetApp = () => {
    setTheme(defaultConfig.theme);
    setLang(defaultConfig.lang);
  };

  return {
    theme,
    lang,
    loading,
    setTheme,
    setLang,
    setLoading,
    initApp,
    resetApp,
  };
});